{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "4\n",
      "9\n",
      "16\n"
     ]
    }
   ],
   "source": [
    "# A generator function that yields square numbers\n",
    "def square_numbers(limit: int):\n",
    "    for n in range(limit):\n",
    "        yield n * n\n",
    "\n",
    "\n",
    "# Use the generator function to compute values\n",
    "for square in square_numbers(5):\n",
    "    print(square)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Generators compute values lazily, meaning they only produce results when explicitly requested."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fetching values on the fly:\n",
      "Computing square for: 0\n",
      "0\n",
      "Computing square for: 1\n",
      "1\n",
      "Computing square for: 2\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "\n",
    "\n",
    "# A generator that computes the square of numbers with a delay\n",
    "def delayed_squares(limit):\n",
    "    for n in range(limit):\n",
    "        print(f\"Computing square for: {n}\")\n",
    "        time.sleep(1)  # Simulate a delay in computation\n",
    "        yield n * n\n",
    "\n",
    "\n",
    "# Instantiate the generator\n",
    "gen = delayed_squares(3)\n",
    "\n",
    "# Step through the generator manually\n",
    "print(\"Fetching values on the fly:\")\n",
    "print(next(gen))  # Compute square of 0\n",
    "print(next(gen))  # Compute square of 1\n",
    "print(next(gen))  # Compute square of 2"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
